package com.it.water.controller.MessageController;

import com.it.water.component.WebSocketServer;
import com.it.water.utils.SendEmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket 推送控制器
 *
 * @author <a href="mailto:2038322151@qq.com">Miraitowa_zcx</a>
 * @version 1.0
 * @since 2024-03-21
 */
@Slf4j
@Controller
@RequestMapping("/websocket")
public class WebSocketController {

    /**
     * 发送邮件
     */
    @Resource
    private SendEmailUtil emailUtil;

    /**
     * 页面请求
     *
     * @param cid 推送 ID
     * @return ModelAndView
     */
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("cid", cid);
        return mav;
    }

    /**
     * 推送数据接口
     *
     * @param cid     推送 ID
     * @param message 消息
     * @return 推送结果
     */
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Map<String, Object> pushToWeb(@PathVariable String cid, String message) {
        Map<String, Object> result = new HashMap<>();
        try {
            WebSocketServer.sendInfo(message, cid);
            sendStringEmail();
            result.put("status", "success");
        } catch (IOException e) {
            result.put("status", "fail");
            result.put("errMsg", e.getMessage());
            log.error("推送消息失败:{}", e.getMessage());
        }
        return result;
    }

    /**
     * 发送邮件
     */
    public void sendStringEmail() {
        // 测试文本邮件发送（无附件）
        // 接收邮箱地址
        String to = "15688446173@163.com";
        String title = "溺水系统发送的消息";
        String content = "XXX溺水了，请及时处理！";
        emailUtil.sendMessage(to, title, content);
    }
}
